package com.me.learnspring.service;

import com.me.learnspring.controller.request.NewDrinkRequest;
import com.me.learnspring.model.Category;
import com.me.learnspring.model.Drink;
import com.me.learnspring.repository.CategoryRepository;
import com.me.learnspring.repository.DrinkRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class DrinkService {
	@Autowired
	private DrinkRepository drepo;
	
	@Autowired
	private CategoryRepository crepo;
	
	public Drink save(Drink d) {
		return drepo.save(d);
	}
	
	public List<Drink> getByCatgoryId(Long id) {
		
		return drepo.getDrinksByCategory_Id(id);
	}
	
	public Drink getDrink(String name){
		return drepo.getDrinksByName(name);
	}
	
	public Drink saveDrink(NewDrinkRequest drinkRequest) {
		Optional<Category> category = crepo.findById(drinkRequest.getCategoryId());
		
		if (category.isPresent()) {
			Drink drink = new Drink();
			BeanUtils.copyProperties(drinkRequest, drink);
			drink.setCategory(category.get());
			return drepo.save(drink);
		}
		
		return null;
	}
	
	public List<Drink> batchSave(List<NewDrinkRequest> drinkRequests) {
		List<Drink> drinks = new ArrayList<>();
		for (NewDrinkRequest drink : drinkRequests) {
			drinks.add(this.saveDrink(drink));
		}
		return drinks;
	}
	
	public Page<Drink> getPageByCatgoryId(Long categoryId, Pageable pageable) {
		return drepo.getAllByCategory_Id(categoryId,pageable);
	}
	
	public Drink findById(String id) {
		return drepo.findById(Long.valueOf(id)).orElse(null);
	}
}
